package com.wxy.favorites.service;

import cn.hutool.core.util.StrUtil;
import com.wxy.favorites.config.AppConfig;
import com.wxy.favorites.constant.PublicConstants;
import com.wxy.favorites.core.NoRollbackException;
import com.wxy.favorites.dao.QuickNavigationRepository;
import com.wxy.favorites.entity.QuickNavigation;
import com.wxy.favorites.security.ContextUtils;
import com.wxy.favorites.security.SecurityUser;
import com.wxy.favorites.util.AssertUtils;
import com.wxy.favorites.util.HtmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Author wangxiaoyuan
 * @Date 2020/4/24 11:50
 * @Description
 **/
@Slf4j
@Service
@Transactional(noRollbackFor = NoRollbackException.class)
public class QuickNavigationService {

    @Autowired
    private QuickNavigationRepository quickNavigationRepository;

    @Autowired
    private AppConfig appConfig;

    public QuickNavigation save(QuickNavigation quickNavigation) {
        return quickNavigationRepository.save(quickNavigation);
    }

    public List<QuickNavigation> findByUserId(Integer userId) {
        return quickNavigationRepository.findAllByUserIdOrderBySort(userId);
    }

    public void deleteById(Integer id) {
        quickNavigationRepository.deleteById(id);
    }

    public int getMaxSortByUserId(Integer userId) {
        return Optional.ofNullable(quickNavigationRepository.getMaxSortByUserId(userId)).orElse(0);
    }

    public void sort(List<QuickNavigation> dto) {
        Optional.ofNullable(dto).orElse(Collections.emptyList()).forEach(nav -> {
            quickNavigationRepository.updateSort(nav.getId(), nav.getSort());
        });
    }

    public void saveNav(QuickNavigation quickNavigation) {
        SecurityUser user = ContextUtils.getCurrentUser();
        List<QuickNavigation> list = findByUserId(user.getId());
        AssertUtils.isTrue(list == null || list.size() < appConfig.getNavigationLimit(), PublicConstants.NAVIGATION_LIMITED_MSG);
        quickNavigation.setUserId(user.getId());
        // 处理图标
        String icon = HtmlUtils.getIcon(quickNavigation.getUrl());
        quickNavigation.setIcon(StrUtil.isBlank(icon) ? PublicConstants.FAVORITES_ICON_DEFAULT : icon);
        quickNavigation.setSort(getMaxSortByUserId(user.getId()) + 1);
        quickNavigationRepository.save(quickNavigation);
    }
}

